package com.liuwei.msmall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.liuwei.msmall.auth.feign.MemberFeignService;
import com.liuwei.msmall.auth.vo.SocialUserVo;
import com.liuwei.msmall.common.constant.AuthServiceConstant;
import com.liuwei.msmall.common.dto.MemberRespDTO;
import com.liuwei.msmall.common.dto.SocialUserDTO;
import com.liuwei.msmall.common.utils.HttpUtils;
import com.liuwei.msmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname OAuth2Controller
 * @Description TODO
 * @Date 2020/6/26 18:33
 * @Created by 刘
 */
@Slf4j
@Controller
public class OAuth2Controller {


    @Autowired
    private MemberFeignService memberFeignService;


    //退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(AuthServiceConstant.LONGIN_USER);
        return "redirect:http://auth.msmall.com/login.html";
    }



    //接入微信登录
    @GetMapping("/oauth2.0/wx/success")
    public String weixinlogin(@RequestParam(value = "code",required = false) String code, HttpSession session, HttpServletRequest request) throws Exception {

        //拿到微博服务器返回的code码，发送post请求获取accessToken

        System.out.println("获得的code码："+code);

        return "login";
    }




    //接入微博登录
    @GetMapping("/oauth2.0/wb/success")
    public String weibologin(@RequestParam(value = "code",required = false) String code, HttpSession session,HttpServletRequest request) throws Exception {

        //拿到微博服务器返回的code码，发送post请求获取accessToken

        System.out.println("获得的code码："+code);

        //调用apache的 HttpUtils工具类发送http请求
        /**
         * String host, String path, String method,
         Map<String, String> headers,
         Map<String, String> querys,
         Map<String, String> bodys
         */
        Map<String, String> postParam=new HashMap<>();
        postParam.put("client_id","1534072948");
        postParam.put("client_secret","7287d6654b12dce7a12d26abd03c4614");
        postParam.put("grant_type","authorization_code");
        postParam.put("redirect_uri","http://auth.msmall.com/oauth2.0/wb/success");
        postParam.put("code",code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "POST", new HashMap<>(), null, postParam);
        if (response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUserDTO socialUserVo = JSON.parseObject(json, SocialUserDTO.class);
            //调用远程服务进行登录
            R r = memberFeignService.weibologin(socialUserVo);
            if (r.getCode()==0){
                //拿到返回的用户信息
                MemberRespDTO memberRespVo = r.getData("data", new TypeReference<MemberRespDTO>() {});
                log.info("登录成功，用户信息:{}",memberRespVo);
                //将用户信息放到session中（redis中）
                session.setAttribute(AuthServiceConstant.LONGIN_USER,memberRespVo);
                //去除未登录提示
                session.removeAttribute("nologinMsg");
                //获取成功后返回商城首页
                return "redirect:http://msmall.com";
            }

            //请求失败，回到登录页
            return "redirect:http://auth.msmall.com";

        }else {

            //请求失败，回到登录页
            return "redirect:http://auth.msmall.com";
        }

    }



}
